package io.renren.modules.job.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import io.renren.modules.sale.entiy.XYContent;
import io.renren.modules.sale.entiy.XYQuestion;
import io.renren.modules.sale.entiy.XYUser;
import io.renren.modules.sale.service.IXYQA;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 初始化爬取小易问答数据
 *
 * 参数格式：
 * "{\"startPageNum\" : 1000}"
 * 默认从第1000页开始爬取
 */
@Component("initXiaoYiQA")
public class InitXiaoYiQA  implements ITask{

    private static final Logger LOGGER = LoggerFactory.getLogger(InitXiaoYiQA.class);

    // 默认从1000页面开始爬取
    private static final String DEFAULT_PARAMS =
            "{\"jsessionid\" : \"8642BC4AC33D63D8A46BBADDBA8B1287\", " +
            "\"startpagenum\" : 1}";

    // 小易问答请求URL
    private static final String XIAOYI_URL = "https://www.mailizc.com/getQzContentPageList.html";
    private static final String COOKIES = "JSESSIONID={};";
    private static final String REQUEST_BODY = "id=73&page={}&justHost=0&priorLvl=0&contentType=0&appid=mini_hc_2.2.0";

    @Autowired
    IXYQA ixyqa;

    @Override
    public void run(String params) throws InterruptedException {
        String tempParams = DEFAULT_PARAMS;
        if(!("".equals(params))){
            tempParams = params;
        }

        JSONObject paramsJson = JSONObject.parseObject(tempParams);
        int startPageNum = paramsJson.getIntValue("startpagenum");
        String jSessionId = paramsJson.getString("jsessionid");

        HttpRequest httpRequest = HttpUtil
                .createPost(XIAOYI_URL)
                .cookie(StrUtil.format(COOKIES, jSessionId));
        for (int i = startPageNum; i > 0 ; i--) {
            Thread.sleep(1000);
            LOGGER.info("正在采集第" + i + "页！");
            httpRequest.body(StrUtil.format(REQUEST_BODY, i));
            HttpResponse httpResponse = httpRequest.execute();
            JSONObject responseJson = JSONObject.parseObject(httpResponse.body());
            JSONArray qaList = responseJson.getJSONObject("data").getJSONArray("list");
            qaList.toJavaList(JSONObject.class).forEach(x -> {
                XYQuestion xyQuestion = JSONObject.toJavaObject(x, XYQuestion.class);
                // @JSONFiled注解无效，原因未知
                xyQuestion.setQuestionId(xyQuestion.getId());
                XYContent xyContent = xyQuestion.getContent();
                XYUser xyQuestionUser = xyContent.getQuestionUser();
                XYUser xyAnswerUser = xyContent.getAnswerUser();
                xyContent.setQuestionId(xyQuestion.getQuestionId());
                if (xyQuestionUser != null) {
                    xyContent.setQuestionUserId(xyQuestionUser.getUserId());
                }
                if (xyAnswerUser != null) {
                    xyContent.setAnswerUserId(xyAnswerUser.getUserId());
                }
                try {
                    ixyqa.insertContent(xyContent);
                } catch (DuplicateKeyException e) {
                    LOGGER.info("已有记录");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        LOGGER.info("初始化任务完成。。。");
    }

    // 时间格式化
//    private static String formatTime(Date timestamp){
//        return DateUtil.format(timestamp, "yyyy-MM-dd HH:mm:ss");
//    }

    private static String formatTime(String timestampString){
        if (null == timestampString || StrUtil.isEmpty(timestampString)){
            return null;
        }
        Date timestamp = DateUtil.date(Long.parseLong(timestampString));
        return DateUtil.format(timestamp, "yyyy-MM-dd HH:mm:ss");
    }

    public static void main(String[] args) {

        HttpRequest httpRequest = HttpUtil
                .createPost(XIAOYI_URL)
                .cookie("JSESSIONID=8642BC4AC33D63D8A46BBADDBA8B1287;");

        httpRequest.body("id=73&page=2&justHost=0&priorLvl=0&contentType=0&appid=mini_hc_2.2.0");
        HttpResponse httpResponse = httpRequest.execute();
        JSONObject responseJson = JSONObject.parseObject(httpResponse.body());
        JSONArray qaList = responseJson.getJSONObject("data").getJSONArray("list");
        qaList.toJavaList(JSONObject.class).forEach(x -> {
            XYQuestion xyQuestion = JSONObject.toJavaObject(x, XYQuestion.class);
            // @JSONFiled注解无效，原因未知
            xyQuestion.setQuestionId(xyQuestion.getId());
            XYContent xyContent = xyQuestion.getContent();
            XYUser xyQuestionUser = xyContent.getQuestionUser();
            XYUser xyAnswerUser = xyContent.getAnswerUser();
            xyContent.setQuestionId(xyQuestion.getQuestionId());
            if(xyQuestionUser != null) {
                xyContent.setQuestionUserId(xyQuestionUser.getUserId());
            }
            if(xyAnswerUser != null) {
                xyContent.setAnswerUserId(xyAnswerUser.getUserId());
            }
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(xyContent).toString());
            jsonObject.keySet().forEach(y -> {
                System.out.println("#{" + y + "},");
            });
        });

    }

}
